import {createSlice} from '@reduxjs/toolkit'
import axios from 'axios'
import dayjs from 'dayjs'

const billStore = createSlice({
    name:'bill',
    initialState:{
        billList:[],
        currentMonth:dayjs().format('YYYY-MM')
    },
    reducers:{
        setBillList(state,action){
            state.billList=action.payload
        },
        addBillItem(state,action){
            state.billList.push(action.payload); 
        },
        setCurrentMonth(state,action){
            state.currentMonth = action.payload
        },delBillItem(state,action){
            state.billList = state.billList.filter(item=>item.id !== action.payload)
        },updateBillItem(state,action){
            state.billList = state.billList.map(item => 
                item.id === action.payload.id ? action.payload : item
            )
        }
    }
})

const {setBillList,addBillItem,setCurrentMonth,delBillItem,updateBillItem} = billStore.actions

//获取账单
const getBillList = ()=>{
    return async (dispatch,getState)=>{
        const { billList } = getState().bill
        if (billList.length !== 0){
            return
        }
        try {
            const res = await axios.get('http://192.168.0.50:8888/ka')
            dispatch(setBillList(res.data))
        } catch (error) {
            console.log("错误",error)
        }
    }
}

//添加一个账单
const addBillList = (data) => async (dispatch) => {
  try {
    const res = await axios.post('http://192.168.0.50:8888/ka', data);
    // 成功后在本地直接更新状态（避免重新请求）
    dispatch(addBillItem(res.data));
  } catch (error) {
    console.error("添加失败:", error);
  }
}

//更新一个账单
const updateBillList = (data) => async (dispatch) => {
  try {
    const res = await axios.put(`http://192.168.0.50:8888/ka/${data.id}`, data);
    // 成功后在本地直接更新状态（避免重新请求）
    dispatch(updateBillItem(res.data));
  } catch (error) {
    console.error("更新失败:", error);
  }
}

//删除一个账单
const delBillList = (id) => async (dispatch) => {
  try {
    const res = await axios.delete(`http://192.168.0.50:8888/ka/${id}`);
    // 成功后在本地直接更新状态（避免重新请求）
    console.log(res)
    console.log(res.data.id)
    dispatch(delBillItem(res.data.id));
  } catch (error) {
    console.error("删除失败:", error);
  }
}

const reducer = billStore.reducer

export {getBillList,addBillList,delBillList,updateBillList,setCurrentMonth}
export default reducer
